<template>
  <div class="file-preview" ref="filePreviewRef">
    <div class="preview-header">
      <div class="file-info">
        <el-icon class="file-icon">
          <DocumentCopy v-if="fileType === 'document' || fileType === 'presentation' || fileType === 'spreadsheet'" />
          <Memo v-else-if="fileType === 'markdown'" />
          <VideoPlay v-else-if="fileType === 'video'" />
          <Picture v-else-if="fileType === 'image'" />
          <Document v-else />
        </el-icon>
        <span class="file-name">{{ fileName }}</span>
      </div>
      <div class="file-actions">
        <el-button type="default" size="small" @click="$emit('back')" class="back-button">
          <el-icon class="mr-1"><Back /></el-icon>
          返回
        </el-button>
        <el-button 
          type="primary" 
          size="small" 
          @click="downloadFile"
          v-if="permissionStore.canDownload"
        >
          <el-icon class="mr-1"><Download /></el-icon>
          下载
        </el-button>
        <el-tooltip 
          v-else 
          :content="permissionStore.downloadDisabledMessage" 
          placement="top"
        >
          <el-button 
            type="info" 
            size="small" 
            disabled
          >
            <el-icon class="mr-1"><Download /></el-icon>
            下载
          </el-button>
        </el-tooltip>
        <el-button 
          type="success" 
          size="small" 
          @click="toggleFullscreen"
        >
          <el-icon class="mr-1">
            <FullScreen v-if="!isFullscreen" />
            <Aim v-else />
          </el-icon>
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
      </div>
    </div>
    
    <div class="preview-content" ref="previewContentRef">
      <!-- 加载中状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner">
          <el-icon class="is-loading loading-icon"><Loading /></el-icon>
          <span class="loading-text">文档加载中...</span>
        </div>
        <el-skeleton :rows="10" animated class="loading-skeleton" />
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <el-empty description="文件加载失败">
          <template #image>
            <el-icon class="error-icon"><WarningFilled /></el-icon>
          </template>
          <template #description>
            <p class="error-text">{{ error }}</p>
          </template>
          <el-button type="danger" @click="loadFile">
            <el-icon class="mr-1"><RefreshRight /></el-icon>
            重试
          </el-button>
        </el-empty>
      </div>
      
      <!-- Office文档预览 (PDF, Word, PPT, Excel) -->
      <div v-else-if="isOfficeDocument" class="office-container">
        <iframe
          v-if="officeViewerUrl"
          :src="officeViewerUrl"
          class="office-viewer"
          frameborder="0"
          allowfullscreen
        ></iframe>
      </div>
      
      <!-- Markdown预览 -->
      <div v-else-if="fileType === 'markdown'" class="markdown-container">
        <MdPreview 
          v-model="fileContent" 
          previewOnly
          :editorId="editorId"
          :toolbars="[]"
          preview-theme="github"
          code-theme="github"
          :noMermaid="false"
          :noKatex="false"
          :noIcons="true"
          style="border: none;"
        />
      </div>
      
      <!-- HTML预览 -->
      <div v-else-if="fileType === 'html'" class="html-container">
        <iframe
          v-if="fileUrl"
          :src="fileUrl"
          class="html-viewer"
          frameborder="0"
          sandbox="allow-same-origin allow-scripts"
          allowfullscreen
        ></iframe>
      </div>
      
      <!-- 图片预览 -->
      <div v-else-if="fileType === 'image'" class="image-container">
        <img :src="fileUrl" alt="图片预览" class="preview-image" />
      </div>
      
      <!-- 视频预览 -->
      <div v-else-if="fileType === 'video'" class="video-container">
        <video controls class="preview-video">
          <source :src="fileUrl" :type="'video/' + getFileExtension(fileName)">
          您的浏览器不支持视频标签
        </video>
      </div>
      
      <!-- 不支持的文件类型 -->
      <div v-else class="unsupported-container">
        <el-empty description="不支持的文件类型">
          <template #image>
            <el-icon class="unsupported-icon"><QuestionFilled /></el-icon>
          </template>
          <template #description>
            <p class="unsupported-text">当前仅支持预览文档、Markdown、图片和视频文件</p>
          </template>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Document, DocumentCopy, Memo, VideoPlay, Picture, Download, 
         Loading, WarningFilled, QuestionFilled, RefreshRight, Back,
         FullScreen, Aim } from '@element-plus/icons-vue';
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { getFileType } from '../../utils/dataService';
import { usePermissionStore } from '../../store';

const props = defineProps({
  fileUrl: {
    type: String,
    required: true
  },
  fileName: {
    type: String,
    default: '未命名文件'
  },
  fileType: {
    type: String,
    default: 'document' // document, markdown, video, image, html, presentation, spreadsheet
  }
});

const emit = defineEmits(['back']);

// 状态管理
const loading = ref(true);
const error = ref(null);
const fileContent = ref('');
const editorId = ref(`preview-md-${Date.now()}`);
const permissionStore = usePermissionStore();
const previewContentRef = ref(null);
const filePreviewRef = ref(null);
const isFullscreen = ref(false);

// 判断是否为Office文档
const isOfficeDocument = computed(() => {
  // 检查文件类型
  if (['document', 'presentation', 'spreadsheet', 'pdf', 'word', 'powerpoint', 'excel'].includes(props.fileType)) {
    return true;
  }
  
  // 如果类型不明确，通过文件扩展名判断
  const extension = getFileExtension(props.fileName).toLowerCase();
  const officeExtensions = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
  
  return officeExtensions.includes(extension);
});

// Office文档查看器URL
const officeViewerUrl = computed(() => {
  if (!isOfficeDocument.value) return '';
  
  // 获取文件扩展名
  const extension = getFileExtension(props.fileName).toLowerCase();
  
  // 对于PDF，直接使用浏览器内置查看器
  if (extension === 'pdf' || props.fileType === 'pdf') {
    console.log('使用浏览器内置PDF查看器:', props.fileUrl);
    return props.fileUrl;
  }
  
  // 对于其他Office文档，使用Microsoft Office Online Viewer
  const encodedUrl = encodeURIComponent(props.fileUrl);
  console.log('使用Office Online查看器:', props.fileUrl);
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`;
});

// 获取文件扩展名
const getFileExtension = (fileName) => {
  const extension = fileName.split('.').pop().toLowerCase();
  return extension;
};

// 加载文件内容
const loadFile = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    if (props.fileType === 'markdown') {
      await loadMarkdownFile();
    } else if (isOfficeDocument.value || props.fileType === 'html' || props.fileType === 'image' || props.fileType === 'video') {
      // 这些类型通过iframe或原生标签直接处理，无需额外加载
      loading.value = false;
    } else {
      error.value = `不支持的文件类型: ${props.fileType}`;
    }
  } catch (err) {
    console.error('加载文件失败:', err);
    error.value = '文件加载失败，请检查文件路径或格式是否正确';
  } finally {
    loading.value = false;
  }
};

// 加载Markdown文件
const loadMarkdownFile = async () => {
  const response = await fetch(props.fileUrl);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  fileContent.value = await response.text();
};

// 下载文件
const downloadFile = () => {
  if (!permissionStore.canDownload) {
    ElMessage({
      type: 'warning',
      message: permissionStore.downloadDisabledMessage || '您没有下载权限'
    });
    return;
  }
  
  try {
    const link = document.createElement('a');
    link.href = props.fileUrl;
    link.download = props.fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage({
      type: 'success',
      message: '文件下载已开始'
    });
  } catch (err) {
    console.error('下载文件失败:', err);
    ElMessage({
      type: 'error',
      message: '文件下载失败，请重试'
    });
  }
};

// 切换全屏模式
const toggleFullscreen = () => {
  const element = filePreviewRef.value;
  
  if (!element) return;
  
  if (!isFullscreen.value) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) { /* Firefox */
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) { /* IE/Edge */
      element.msRequestFullscreen();
    }
    isFullscreen.value = true;
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) { /* Firefox */
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE/Edge */
      document.msExitFullscreen();
    }
    isFullscreen.value = false;
  }
};

// 监听文件URL变化
watch(() => props.fileUrl, () => {
  if (props.fileUrl) {
    loadFile();
  }
});

// 监听全屏状态变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement || 
                      !!document.mozFullScreenElement || 
                      !!document.webkitFullscreenElement || 
                      !!document.msFullscreenElement;
};

// 组件挂载时加载文件
onMounted(() => {
  if (props.fileUrl) {
    loadFile();
  }
  
  // 添加全屏状态变化监听器
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
});

// 组件卸载时移除监听器
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
});
</script>

<style scoped>
.file-preview {
  width: 100%;
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #3b82f6;
}

.file-name {
  font-size: 18px;
  font-weight: 500;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.preview-content {
  flex: 1;
  overflow: auto;
  min-height: 100vh;
}

.loading-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.loading-icon {
  font-size: 40px;
  color: #3b82f6;
}

.loading-text {
  color: #3b82f6;
  font-weight: 500;
  margin-top: 8px;
}

.loading-skeleton {
  margin-top: 32px;
  width: 100%;
  max-width: 600px;
}

.error-container,
.unsupported-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
}

.error-icon {
  font-size: 60px;
  color: #ef4444;
}

.error-text {
  color: #ef4444;
  margin-top: 16px;
  margin-bottom: 16px;
}

.unsupported-icon {
  font-size: 60px;
  color: #6b7280;
}

.unsupported-text {
  color: #6b7280;
  margin-top: 16px;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.back-button {
  margin-right: 4px;
}

/* Office文档预览样式 */
.office-container {
  height: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.office-viewer {
  width: 100%;
  height: 100%;
  border: none;
}

/* Markdown预览样式 */
.markdown-container {
  height: 100%;
  min-height: 100vh;
}

/* 重点：消除编辑器的左侧编辑区域，只保留预览区域 */
.markdown-container :deep(.md-editor) {
  height: 100%;
  min-height: 100vh;
  border: 0 !important;
  display: flex;
}

.markdown-container :deep(.md-editor-content) {
  margin-left: 0 !important; /* 移除左侧边距 */
  display: flex;
  min-height: 100vh;
  width: 100% !important;
}

.markdown-container :deep(.md-editor-input) {
  display: none !important; /* 隐藏输入区域 */
}

.markdown-container :deep(.md-editor-preview) {
  width: 100% !important; /* 预览区域占满宽度 */
  min-height: 100vh;
  border-left: none !important; /* 移除左侧边框 */
}

.markdown-container :deep(.md-editor-preview-wrapper) {
  padding: 24px;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
}

/* HTML预览样式 */
.html-container {
  height: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.html-viewer {
  width: 100%;
  height: 100%;
  border: none;
}

/* 图片预览样式 */
.image-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #111827;
  padding: 16px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 视频预览样式 */
.video-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #111827;
  padding: 16px;
}

.preview-video {
  max-width: 100%;
  max-height: 100%;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 全屏模式样式 */
.preview-content:fullscreen {
  background-color: white;
  padding: 20px;
  overflow: auto;
}

.preview-content:fullscreen .office-container,
.preview-content:fullscreen .markdown-container,
.preview-content:fullscreen .html-container,
.preview-content:fullscreen .image-container,
.preview-content:fullscreen .video-container {
  height: 100vh;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .file-actions {
    margin-top: 8px;
  }
  
  .file-name {
    max-width: 250px;
  }
}
</style> 